﻿using System.Collections;
using System.Collections.Generic;
using Dragon.Library.Framework.Entity.Search.Query;
using Dragon.Library.Utility.NHibernate;
using NHibernate;

namespace Dragon.Library.Framework.Dao
{
    public partial class BaseDao<T, TKeyT>
    {
        public IList<T> Select(QueryGroup queryGroup, QueryLevel queryLevel)
        {
            switch (queryLevel)
            {
                case QueryLevel.Advanced:
                    return SelectAdvanced(queryGroup);
                case QueryLevel.General:
                    return Select(queryGroup);
            }
            return new List<T>();
        }

        private IList<T> Select(QueryGroup queryGroup)
        {
            ISession session = SessionFactory.GetSession(SessionKey, ConfigFileName);
            ICriteria criteria = session.CreateCriteria(typeof(T));
            if (queryGroup != null && queryGroup.Top > 0)
                criteria.SetMaxResults(queryGroup.Top);
            criteria = CriteriaOrderBuilder(criteria, queryGroup);
            criteria = CriteriaQueryBuilder(criteria, queryGroup);
            return criteria.List<T>();
        }

        public IList<T> Select(QueryString queryString)
        {
            IQuery query = Session.CreateQuery(queryString.SearchString);
            foreach (var parameter in queryString.Parameters)
            {
                query.SetParameter(parameter.Key, parameter.Value);
            }
            return query.List<T>();
        }

        public IList SelectList(QueryString queryString)
        {
            IQuery query = Session.CreateQuery(queryString.SearchString);
            foreach (var parameter in queryString.Parameters)
            {
                query.SetParameter(parameter.Key, parameter.Value);
            }
            return query.List();
        }

        private IList<T> SelectAdvanced(QueryGroup queryGroup)
        {
            ISession session = SessionFactory.GetSession(SessionKey, ConfigFileName);
            ICriteria criteria = session.CreateCriteria(typeof(T));
            if (queryGroup != null && queryGroup.Top > 0)
                criteria.SetMaxResults(queryGroup.Top);
            criteria = CriteriaOrderBuilderAdvanced(criteria, queryGroup);
            criteria = CriteriaQueryBuilderAdvanced(criteria, queryGroup);
            return criteria.List<T>();
        }
    }
}
